<?php

namespace App\Listeners;

use App\BO\OrderStatus\Events\OrderServiceFinishEvent;
use App\BO\PaymentState\Event\PaySuccessEvent;
use App\BO\PaymentState\Event\RefundSuccessEvent;
use App\Entities\PaymentEntity;
use App\ServicesNew\NewServiceTrait;
use Illuminate\Support\Facades\Log;

class DistributorEventSubscriber
{
    use NewServiceTrait;

    public const  SUBSCRIBER = DistributorEventSubscriber::class;

    /**
     * 支付成功，进行分销记录
     * @param PaySuccessEvent $event
     */
    public function onPaySuccess(PaySuccessEvent $event)
    {
        $paymentEntity = $event->getPayment();

        $userEntity = $this->getPaymentService()->getUserEntityByPayment($paymentEntity);
        if (is_null($userEntity)) {
            Log::warning('用户不存在');
            return;
        }
        $this->getDistributorService()->giveProfit($userEntity->getUserId(), $paymentEntity);
    }

    /**
     * @param OrderServiceFinishEvent $event
     */
    public function onOrderServiceFinish(OrderServiceFinishEvent $event)
    {
        $orderEntity = $event->getOrder();
        $paymentEntity = PaymentEntity::findByTradeNo($orderEntity->getNo());
        if (is_null($paymentEntity)) {
            Log::warning('用户不存在');
            return;
        }
        $this->getDistributorService()->confirm($paymentEntity);
    }

    /**
     * @param RefundSuccessEvent $event
     */
    public function onRefundSuccess(RefundSuccessEvent $event)
    {
        $paymentEntity = $event->getPayment();
        $this->getDistributorService()->refund($paymentEntity);
    }


    /**
     * 为订阅者注册监听器。
     *
     * @param  \Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            RefundSuccessEvent::class,
            self::SUBSCRIBER . '@onRefundSuccess'
        );

        $events->listen(
            PaySuccessEvent::class,
            self::SUBSCRIBER . '@onPaySuccess'
        );

        $events->listen(
            OrderServiceFinishEvent::class,
            self::SUBSCRIBER . '@onOrderServiceFinish'
        );
    }
}
